package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"time"

	"github.com/gobwas/ws"
	"github.com/gobwas/ws/wsutil"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/net"
)

type configuration struct {
	Token     string
	TargetNet string
	WsServer  string
}

type ColorGroup struct {
	Token string `json:"token"`
	Rx    uint64 `json:"rx"`
	Tx    uint64 `json:"tx"`
	Mem   uint64 `json:"mem"`
	Time  int64  `json:"time"`
}

func main() {
	ctx := context.Background()

	file, _ := os.Open("go.json")
	defer file.Close()
	decoder := json.NewDecoder(file)
	conf := configuration{}

	err := decoder.Decode(&conf)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
	fmt.Println(conf)

	for {
		conn, _, _, err := ws.DefaultDialer.Dial(ctx, conf.WsServer)
		var oldRx uint64 = 0
		var oldTx uint64 = 0
		for {
			if err != nil {
				// handle error
				break
			}
			//tst := []byte("little test")
			// send message
			// err = wsutil.WriteClientMessage(conn, ws.OpText, tst)
			// if err != nil {
			// 	// handle error
			// 	break
			// }
			// receive message
			// msg, _, err := wsutil.ReadServerData(conn)
			// if err != nil {
			// 	// handle error
			// }
			// fmt.Printf("%v", msg)
			memInfo, _ := mem.VirtualMemory()
			//fmt.Printf("mem info:%v\n", memInfo)
			info, _ := net.IOCounters(true)

			for _, v := range info {
				if v.Name == conf.TargetNet {
					if oldRx == 0 {
						oldRx = v.BytesRecv
						oldTx = v.BytesSent
						continue
					}
					temp := ColorGroup{
						Token: conf.Token,
						Rx:    (v.BytesRecv - oldRx) / 1024,
						Tx:    (v.BytesSent - oldTx) / 1024,
						Mem:   (memInfo.Used / (1024 * 1024)),
						Time:  time.Now().Unix(),
					}
					//kb
					oldRx = v.BytesRecv
					oldTx = v.BytesSent
					test, _ := json.Marshal(&temp)
					fmt.Println(string(test))

					//fmt.Println(v.BytesRecv - oldRx)
					err = wsutil.WriteClientMessage(conn, ws.OpText, test)
					if err != nil {
						// handle error
						break
					}
				}
			}
			if err != nil {
				// handle error
				break
			}
			time.Sleep(time.Duration(1) * time.Second)
		}
		time.Sleep(time.Duration(1) * time.Second)
	}
}
